package com.boarsoft.boar.gateway.activemq.test;

import javax.jms.Connection;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.boarsoft.common.util.JsonUtil;
import com.boarsoft.message.bean.Message;

/**
 * 此类演示了如何使用ActiveMQ的客户端API，以短连接的方式来获取消息<br/>
 * 实际应用中应采用长连接方式，请参见Queue1Consumer1.java
 * 
 * @author Mac_J
 *
 */
public class AmqListenerTest1 {
	private static final Logger log = LoggerFactory.getLogger(AmqListenerTest1.class);

	public static void main(String[] args) throws JMSException {
//		ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://127.0.0.1:61616");
		ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("http://localhost:8080?trace=true");
		// JmsConnectionFactory factory = new
		// JmsConnectionFactory("amqp://192.168.1.12:5672");
		Connection connection = factory.createConnection("admin", "admin");
		connection.start();
		final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
		Destination destination = session.createQueue("queue1");
		final MessageConsumer consumer = session.createConsumer(destination);
		log.info("Waiting for messages...");
		while (true) {
			// 以文本或对象等方式获取消息内容
			String o = ((TextMessage) consumer.receive()).getText();
			// 可以用任何形式对消息进行解析和处理
			Message m = JsonUtil.parseObject(o, Message.class);
			// Object o = ((ObjectMessage) msg).getObject();
			// 此处可从spring容器中获取Queue1Consumer1的实例，并调用其put方法来处理消息
//			Map<String, RecipientStatus> rm = m.getRecipients();
//			for (String r : rm.keySet()) {
//				MessageService ms = (MessageSerivce) applicationContext.getBean(r);
//				ms.put(m);
//			}
			log.info("Received text message {}", m);
		}
	}
}